package com.vst.pushlib;

import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.TextUtils;

public class PushHandler {

    private HandlerThread mPushThead;

    private Handler mPushHandler;

    private String mKey;

    private String mPath;

    private Context mContext;

    private class MsgBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            handle(intent);
        }
    }

    private MsgBroadcastReceiver mMsgBroadcastReceiver;

    public PushHandler(Context ctx, String key) {
        mPushThead = new HandlerThread("Push_thread");
        mPushThead.start();
        mPushHandler = new Handler(mPushThead.getLooper());
        mKey = key;
        mMsgBroadcastReceiver = new MsgBroadcastReceiver();
        ctx.registerReceiver(mMsgBroadcastReceiver, new IntentFilter(PushConstant.getControlAction()));
        mContext = ctx;
    }

    public void setPath(String path) {
        mPath = path;
    }

    /**
     * 
     * @param path
     *            播放视频的uuid
     * @param state
     *            当前播放状态
     * @param msg
     *            附带信息
     */
    public void onStateChanged(final String path, final int state, final String msg) {
        try {
            if (mPushHandler != null) {
                mPushHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        doHttp(URL + "?s=set_status&push=-1&key=" + mKey + "&state=" + state + "&message=" + msg
                                + "&path=" + path, null);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void play() {
        onStateChanged(mPath, PushConstant.STATE_PLAY, "");
    }

    public void pause() {
        onStateChanged(mPath, PushConstant.STATE_PAUSE, "");
    }

    public void error(String reason) {
        onStateChanged(mPath, PushConstant.STATE_ERROR, reason);
    }

    public void complete() {
        onStateChanged(mPath, PushConstant.STATE_COMPLETE, "");
    }

    /**
     * @param path
     *            播放视频的uuid
     * @param pos
     *            当前播放位置
     * @param duration
     *            总时长
     */
    public void onPositionChanged(final String path, final int pos, final int duration) {
        try {
            if (mPushHandler != null) {
                mPushHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        doHttp(URL + "?s=set_status&push=-1&key=" + mKey + "&pos=" + pos + "&duration=" + duration
                                + "&path=" + path, null);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onVolumeChanged(final String path, final int volume, final boolean isMute) {
        try {
            if (mPushHandler != null) {
                mPushHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        doHttp(URL + "?s=set_volume&push=-1&key=" + mKey + "&volume=" + volume + "&mute=" + isMute
                                + "&path=" + path, null);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清理
     */
    public void destory() {
        if (mPushHandler != null) {
            mPushHandler.removeCallbacksAndMessages(null);
            mPushThead.quit();
            mPushHandler = null;
        }

        if (mMsgBroadcastReceiver != null) {
            mContext.unregisterReceiver(mMsgBroadcastReceiver);
            mMsgBroadcastReceiver = null;
        }

    }

    public static void bind(final Context ctx, final String appid, final String channelId, final String userid,
            final String packageStr) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("com", packageStr));
                    params.add(new BasicNameValuePair("user_id", userid));
                    // params.add(new BasicNameValuePair("appid", appid));
                    // params.add(new BasicNameValuePair("channelid",
                    // channelId));
                    String str = doHttp(
                    /* URL + "index.php?s=bind", */"http://my.91vst.com/api/regpush.php", params);
                    JSONObject json = new JSONObject(str);
                    if (!json.has("softkey")) {
                        return;
                    }
                    final String key = json.getString("softkey");
                    if (TextUtils.isEmpty(key)) {
                        return;
                    }
                    PushConstant.setBindKey(key);
                    PushConstant.getSp(ctx).edit().putString(PushConstant.EXTRA_KEY, key).commit();
                    Intent intent = new Intent(PushConstant.ACTION_BINDKEY_BY_PUSH).putExtra(PushConstant.EXTRA_KEY,
                            key);
                    intent.putExtra(PushConstant.PUSH_PKG, packageStr);
                    ctx.sendStickyBroadcast(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    static String doHttp(String url, ArrayList<NameValuePair> pairs) {
        return doHttp(url, pairs, null);
    }

    static String doHttp(String url, ArrayList<NameValuePair> pairs, Header[] headers) {
        try {
            HttpClient client = new DefaultHttpClient();
            HttpUriRequest request = new HttpPost(url);
            if (pairs != null) {
                ((HttpPost) request).setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
            }
            if (headers != null) {
                request.setHeaders(headers);
            }
            HttpResponse response = client.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static final String URL = "http://push.91vst.com/wx/";

    /**
     * 
     * @return 返回一个服务器生成的key
     */
    public String getKey() {
        return mKey;
    }

    public void handle(Intent newIntent) {
        if (newIntent == null || mCallback == null) {
            return;
        }
        if (newIntent.hasExtra(PushConstant.EXTRA_STATE)) {
            switch (newIntent.getIntExtra(PushConstant.EXTRA_STATE, PushConstant.STATE_IDLE)) {
            case PushConstant.STATE_PLAY:
                mCallback.start();
                break;
            case PushConstant.STATE_PAUSE:
                mCallback.pause();
                break;
            case PushConstant.STATE_STOP:
                mCallback.stop();
                break;
            case PushConstant.STATE_COMPLETE:
                mCallback.complete();
                break;
            case PushConstant.STATE_ERROR:
                mCallback.error();
                break;
            }
        } else if (newIntent.hasExtra(PushConstant.EXTRA_POS)) {
            mCallback.seekTo(newIntent.getIntExtra(PushConstant.EXTRA_POS, 0));
        } else if (newIntent.hasExtra(PushConstant.EXTRA_VOLUME)) {
            mCallback.setVolume(newIntent.getBooleanExtra(PushConstant.EXTRA_MUTE, false),
                    newIntent.getIntExtra(PushConstant.EXTRA_VOLUME, 0));
        }
    }

    public void setHandleCallBack(HandleCallback callback) {
        mCallback = callback;
    }

    private HandleCallback mCallback;

    public interface HandleCallback {

        void start();

        void pause();

        void stop();

        void error();

        void complete();

        void seekTo(int position);

        void setVolume(boolean mute, int volume);

    }

    public static String getTitle(Intent newIntent) {
        return newIntent.getStringExtra(PushConstant.EXTRA_TITLE);
    }

    public static boolean isLivePush(Intent newIntent) {
        return newIntent.getBooleanExtra(PushConstant.EXTRA_LIVE, false);
    }

    public static String getVid(Intent newIntent) {
        return newIntent.getStringExtra(PushConstant.EXTRA_VID);
    }

}
